<?php 
namespace app\admin\model;
use think\Model;


class AuthGroupAccess extends Model {

	/**
	 * 获取组下的成员
	 * @param  int $group_id 组ID
	 * @return mixed array or null
	 */
	public static function getGroupUsers($group_id)
	{
	    return self::join('user','wq_auth_group_access.uid=wq_user.id','INNER')->where(['group_id'=>$group_id])->select();
	}


	/**
	 * 把用户加入到组
	 * @param int $uid 用户ID
	 * @param boolean
	 */
	public  function addToGroup($uid='',$gid=''){

	    $params=getParams();

	    $uids=array_filter(explode(',',$uid?$uid:$params['uid']));

	    $valid_user=db('user')->where(['status'=>1,'id'=>['IN',$uids]])->column('id');

	    if(empty($valid_user)){
	    	$this->error='用户不存在！';
	    	return false;
	    }

	    $group_id=$gid?$gid:$params['group_id'];

	    //未做合法验证
	    foreach($valid_user as $uid){
	    	$data=['uid'=>$uid,'group_id'=>$group_id];

	    	if(!self::where($data)->find()){
				self::insert($data);
			}
	    }

	    return true;

	}

	/**
	 * 返回用户所属用户组信息
	 * @param  int    $uid 用户id
	 * @return array  用户所属的用户组 array(
	 *                                         array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
	 *                                         ...)
	 */
	static public function getUserGroup($uid){
	    static $groups = array();
	    if (isset($groups[$uid]))
	        return $groups[$uid];
	    $prefix = config('prefix');
	    $user_groups = \think\Db::table($prefix.self::AUTH_GROUP_ACCESS.' a')
	        ->field('uid,group_id,title,description,rules')
	        ->join ($prefix.self::AUTH_GROUP." g ","a.group_id=g.id")
	        ->where("a.uid='$uid' and g.status='1'")
	        ->select();
	    $groups[$uid]=$user_groups?$user_groups:array();
	    return $groups[$uid];
	}


	/**
	 * 从用户组删除用户
	 * @param  integer $uid      用户ID
	 * @param  integer $group_id 组ID
	 * @return boolean
	 */
	public static function deleteGroupUser($uid=0,$group_id=0)
	{	
		$params=getParams();

		$uid=$uid?$uid:$params['uid'];

		$group_id=$group_id?$group_id:$params['group_id'];

		return self::where(['uid'=>$uid,'group_id'=>$group_id])->delete();

	}


}

?>